package ru.lukyanets.transmission.client.ui.control;

import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TableCell;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;

import static ru.lukyanets.transmission.client.util.UnitsUtil.getPercentText;

/**
 * A class containing a {@link TableCell} implementation that draws a
 * {@link ProgressBar} node with text inside the cell.
 * Based on {@link javafx.scene.control.cell.ProgressBarTableCell}
 *
 * @param <S> The type of the elements contained within the TableView.
 * @author Sergey Lukyanets
 */
public class ProgressBarTextTableCell<S> extends TableCell<S, Double> {

    private final ProgressBar progressBar;
    private final Text text;
    private final StackPane stackPane;


    /**
     * Creates a default {@link ProgressBarTextTableCell} instance
     */
    public ProgressBarTextTableCell() {
        this.getStyleClass().add("progress-bar-table-cell");

        this.progressBar = new ProgressBar();
        this.progressBar.setMaxWidth(Double.MAX_VALUE);

        this.text = new Text();
        this.stackPane = new StackPane();
        stackPane.getChildren().setAll(progressBar, text);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void updateItem(Double item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setGraphic(null);
        } else {
            progressBar.setProgress(item);
            text.setText(getPercentText(item));
            setGraphic(stackPane);
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
        }
    }
}
